package mapeditor.treepanel;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.net.URL;

import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;

public class TreePanel extends JPanel implements TreeSelectionListener
{

	private JTree	tree;

	public TreePanel() {
		super( );
		setLayout(new GridLayout(1,1));
		DefaultMutableTreeNode top = new DefaultMutableTreeNode( "Items" );
		createNodes( top );
		tree = new JTree( top );
		tree.getSelectionModel( ).setSelectionMode(
				TreeSelectionModel.SINGLE_TREE_SELECTION );

		// Listen for when the selection changes.
		tree.addTreeSelectionListener( this );
		tree.setPreferredSize( new Dimension( 150 , 5000 ) );
		add( tree );
	}

	@Override
	public void valueChanged( TreeSelectionEvent e )
	{
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree
				.getLastSelectedPathComponent( );

		if ( node == null )
			return;

		Object nodeInfo = node.getUserObject( );
		if ( node.isLeaf( ) ) {
			System.out.println( nodeInfo.toString( ) );
		}
	}

	private void createNodes( DefaultMutableTreeNode top )
	{
		DefaultMutableTreeNode category = null;
		DefaultMutableTreeNode book = null;

		category = new DefaultMutableTreeNode( "Movables" );
		top.add( category );

		DefaultMutableTreeNode cat2 = new DefaultMutableTreeNode( ("Specials") );
		category.add( cat2 );
		book = new DefaultMutableTreeNode( new TreeItem( "Terre" ,
				"tutorial.html" ) );
		cat2.add( book );

		// original Tutorial
		book = new DefaultMutableTreeNode( new TreeItem( "Firesword" ,
				"tutorial.html" ) );
		category.add( book );

		// Tutorial Continued
		book = new DefaultMutableTreeNode( new TreeItem( "Dragon Hammer" ,
				"tutorialcont.html" ) );
		category.add( book );

		// JFC Swing Tutorial
		book = new DefaultMutableTreeNode( new TreeItem( "Helmet" ,
				"swingtutorial.html" ) );
		category.add( book );

		// Bloch
		book = new DefaultMutableTreeNode( new TreeItem( "Wazap" , "asd" ) );
		category.add( book );

		// Arnold/Gosling
		book = new DefaultMutableTreeNode( new TreeItem( "Leather piece" ,
				"arnold.html" ) );
		category.add( book );

		// Chan
		book = new DefaultMutableTreeNode( new TreeItem( "2-h rune sword" ,
				"chan.html" ) );
		category.add( book );

		category = new DefaultMutableTreeNode( "Housing" );
		top.add( category );

		// VM
		book = new DefaultMutableTreeNode( new TreeItem( "Table" , "vm.html" ) );
		category.add( book );

		// Language Spec
		book = new DefaultMutableTreeNode( new TreeItem( "Wall" , "jls.html" ) );
		category.add( book );
	}

	private class TreeItem
	{
		public String	itemName;
		public URL		bookURL;

		public TreeItem( String book , String filename ) {
			itemName = book;
		}

		public String toString()
		{
			return itemName;
		}
	}

}
